"""LLM Plays Pokemon 主入口模块"""

import sys
import logging
import os
import threading
from pathlib import Path

from llm_pokemon.core.config import load_config, setup_logging
from llm_pokemon.core.game_loop import GameLoop
from llm_pokemon.core.ai_loop import AILoop

logger = logging.getLogger(__name__)


def main():
    """主程序入口点"""
    try:
        # 加载配置
        config = load_config()
        
        # 设置日志
        setup_logging(config)
        
        logger.info("启动 LLM Plays Pokemon 系统...")
        
        # 配置已在前面加载
        
        # 设置ROM路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        parent_dir = os.path.dirname(current_dir)
        rom_path = os.path.join(parent_dir, "pkm.gb")
        config["emulator"]["rom_path"] = rom_path
        config["emulator"]["type"] = "pyboy"  # 使用PyBoy模拟器
        
        logger.info(f"设置ROM路径: {rom_path}")
        
        # 初始化游戏主循环
        game_loop = GameLoop(config)
        
        # 注释掉AI决策循环相关代码
        # 初始化AI决策循环
        # ai_loop = AILoop(config, game_loop.get_shared_state(), game_loop.emulator_tool)
        
        # 创建并启动AI决策循环线程
        # ai_thread = threading.Thread(target=ai_loop.start)
        # ai_thread.daemon = True
        # ai_thread.start()
        
        # logger.info("AI决策循环线程已启动")
        
        # 启动游戏主循环（在主线程中运行）
        # 由于没有AI线程，传入None
        game_loop.start(None)
        
    except KeyboardInterrupt:
        logger.info("用户中断，正在关闭系统...")
    except Exception as e:
        logger.exception(f"系统运行时发生错误: {e}")
    finally:
        logger.info("系统已关闭")


if __name__ == "__main__":
    main()